import router from './router'
import store  from './store'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import { getToken } from '@/utils/auth'


const whiteList = ['/login']

router.beforeEach((to, from, next) => {
    //首先打开进度条
    NProgress.start()

    if (!getToken()) {
        console.log('没有token')
        if (whiteList.indexOf(to.path) != -1) {
            console.log(to.path + ',在白名单中')
            next()
        } else {
            //如果没有在白名单中，重定向login
            console.log('不在白名单中,需要跳转. to:' + to.fullPath)
            next(`/login?redirect=${to.fullPath}`)
        }
    } else {
        console.log('有token')
        if (to.path === '/login') {
            next({ path: '/' })
            NProgress.done()
        } else {
            if (store.getters.roles.length === 0) {
                store.dispatch('GetInfo').then(res => {
                    const roles = res.roles
                    console.log(roles)
                    store.dispatch('GenerateRoutes', { roles })
                        .then(accessRoutes => {
                            console.log('accessRoutes-------------------')
                            console.log(accessRoutes)
                            router.addRoutes(accessRoutes)
                            next({ ...to, replace: true })
                    })
                })
            } else {
                next()
            }
        }
        NProgress.done()
    }

    next()
})

router.afterEach( () => {
    NProgress.done()
})
